﻿using System;

using NUnit.Framework;

using OpenQA.Selenium;
using System.Threading;

namespace MVCBootstrap.Tests.WebUI {

	[TestFixture]
	public class LockTest {
		private static IWebDriver driver;

		#region Initialization and cleanup
		[TestFixtureSetUp]
		public static void TestInitialize() {
			driver = TestHelper.GetDriver();
		}

		[TestFixtureTearDown]
		public static void TestCleanup() {
			if (driver != null) {
				driver.Close();
			}
		}
		#endregion

		private const Int32 maxInvalidPasswordAttempts = 3;
		//private const Int32 passwordAttemptWindow
		private const Int32 passwordAttemptLockoutDuration = 2;

		[Test]
		public void Locked() {
			driver.VisitURL("account/logon");

			driver.InsertText("UserName", "Mr. Test");
			driver.InsertText("Password", "123456");
			driver.FindButton("Log On").Click();

			Assert.AreEqual(1, driver.FindElements(By.XPath("//a[@href=\"/Account/LogOff\"]")).Count, "Log on failed");

			driver.FindElement(By.XPath("//a[@href=\"/Account/LogOff\"]")).Click();

			Assert.AreEqual(1, driver.FindElements(By.XPath("//a[@href=\"/Account/LogOn\"]")).Count, "Log off failed");

			for (Int32 index = 0; index <= maxInvalidPasswordAttempts; index++) {
				driver.VisitURL("account/logon");

				driver.InsertText("UserName", "Mr. Test");
				driver.InsertText("Password", "fewgwegwg");
				driver.FindButton("Log On").Click();

				Thread.Sleep(1000);

				Assert.AreEqual(true, driver.PageSource.Contains("Login was unsuccessful"), "No error displayed");
			}

			driver.VisitURL("account/logon");

			driver.InsertText("UserName", "Mr. Test");
			driver.InsertText("Password", "123456");
			driver.FindButton("Log On").Click();

			Thread.Sleep(1000);

			Assert.AreEqual(true, driver.PageSource.Contains("Login was unsuccessful"), "No error displayed");

			// Lock-out duration + 5 seconds!
			Thread.Sleep(1000 * 60 * passwordAttemptLockoutDuration + 5000);

			driver.VisitURL("account/logon");

			driver.InsertText("UserName", "Mr. Test");
			driver.InsertText("Password", "123456");
			driver.FindButton("Log On").Click();

			Thread.Sleep(1000);

			Assert.AreEqual(1, driver.FindElements(By.XPath("//a[@href=\"/Account/LogOff\"]")).Count, "Log on failed");
		}
	}
}